package com.exampl.springstack.common.RestTemplateUtils.utils;

import com.exampl.springstack.common.GlobalConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;


import java.util.HashMap;
import java.util.Map;

/**
 * @author qiangfanghao
 * @date
 * http || https RestTemplate 请求工具类
 * jdk 8u301 以上调整了 SSL 权限 需要 将 java.security 中的 SSLv3注释 之后使用
 * Spring 5中 建议使用 WebClient(reactive版的RestTemplate)
 */
@Slf4j
@Component()
public class HttpRequestUtils {

    @Autowired
    @Qualifier("restHttpTemplate")
    private RestTemplate restHttpTemplate;

    @Autowired
    @Qualifier("restHttpsTemplate")
    private RestTemplate restHttpsTemplate;

    /**
     * rest get请求 参考
     * @param getRequestUri
     * @return
     */
    public String getRequestMapping(String getRequestUri){

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        // 设置token
//        headers.add("token", "");

        //可以在map中设置 请求参数
        Map<String, String> params = new HashMap<>();
//        HttpEntity<?> requestEntity = new HttpEntity<>(params, headers);

        HttpEntity<String> request = new HttpEntity<>(null, headers);

        ResponseEntity<String> response = null;

        try {
            // 判断是否为 http 请求
            if (getRequestUri.startsWith(GlobalConst.HTTP_HEAD)){
                response = restHttpTemplate.exchange(getRequestUri, HttpMethod.GET, request, String.class);
//                response = restHttpTemplate.getForEntity(getRequestUri, String.class);
            }else {
                response = restHttpsTemplate.exchange(getRequestUri, HttpMethod.GET, request, String.class);
            }
        } catch (HttpClientErrorException e) {
            e.printStackTrace();

            int requestStatus = e.getRawStatusCode();

            //获取请求异常 返回 异常信息
//            if (requestStatus == GlobalConst.UNAUTHORIZED_STATUS) {
//                throw  new PEException(ResultEnum.EXCEPTION_ERROR_INTERNAL_MEMBER_NULL);
//            } else {
//                throw new PEException(ResultEnum.EXCEPTION_ERROR);
//            }
        }
        //获取放回json数据
        String result = response.getBody();

        if (StringUtils.isBlank(result)){
            log.warn("请求uri->{}获取数据response->{}为空,请联系相关人员进行排查",getRequestUri,result);
        }
        return result;
    }


}
